# coding:utf-8
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QWidget, QStackedWidget, QVBoxLayout
from qfluentwidgets import SearchLineEdit, SegmentedWidget

from common import SingleIcon
from .bird import BirdInterface


class SearchInterface(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.vBoxLayout = QVBoxLayout(self)
        self.searchLineEdit = SearchLineEdit(self)
        self.pivot = SegmentedWidget(self)
        self.stackedWidget = QStackedWidget(self)
        self.birdInterface = BirdInterface(self)

        self.__initWidgets()
        self.initSubInterface()
        self.connectSignals()

    def connectSignals(self):
        self.searchLineEdit.searchButton.setShortcut('Return')
        self.searchLineEdit.searchSignal.connect(self.onSearch)

    def __initWidgets(self):
        self.setObjectName("SearchInterface")
        self.searchLineEdit.setMinimumWidth(500)
        self.searchLineEdit.setClearButtonEnabled(True)
        self.searchLineEdit.setPlaceholderText('请输入关键字搜索')
        self.searchLineEdit.setAlignment(Qt.AlignmentFlag.AlignHCenter)

        self.vBoxLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.vBoxLayout.addWidget(self.searchLineEdit, 0, Qt.AlignmentFlag.AlignHCenter)
        self.vBoxLayout.addWidget(self.pivot, 0, Qt.AlignmentFlag.AlignLeft)
        self.vBoxLayout.addWidget(self.stackedWidget, 1)

        self.stackedWidget.setCurrentWidget(self.birdInterface)
        self.pivot.currentItemChanged.connect(
            lambda k: self.stackedWidget.setCurrentWidget(self.findChild(QWidget, k)))

    def initSubInterface(self):
        self.addSubInterface(self.birdInterface, 'bird', '小鸟壁纸', icon=SingleIcon.BIRD)
        self.pivot.setCurrentItem('bird')

    def addSubInterface(self, widget: QWidget, objectName: str, text: str, icon=None):
        self.stackedWidget.addWidget(widget)
        self.pivot.addItem(routeKey=objectName, text=text, icon=icon)

    def onSearch(self, keyword: str):
        self.birdInterface.loadData(keyword)
